package com.hongxinguoji.manager.admin.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hongxinguoji.manager.admin.pojo.HxAuthFunction;
import com.hongxinguoji.manager.admin.service.IFunctionService;
import com.hongxinguoji.manager.common.util.EasyUIDataGridResult;
import com.hongxinguoji.manager.common.util.HXResult;
import com.hongxinguoji.manager.common.util.IDUtils;

@Controller
@RequestMapping("/admin")
public class FunctionController {

	@Autowired
	private IFunctionService functionService;

	/**
	 * 查询权限列表到数据表格
	 * 
	 * @param page
	 * @param rows
	 * @return
	 */
	@RequestMapping("/functionlist")
	@ResponseBody
	public EasyUIDataGridResult getFunctionList(Integer page, Integer rows) {
		EasyUIDataGridResult result = new EasyUIDataGridResult();
		// 分页处理
		PageHelper.startPage(page, rows);
		List<HxAuthFunction> list = functionService.getFunctionList();
		PageInfo<HxAuthFunction> pageInfo = new PageInfo<>(list);
		result.setTotal(pageInfo.getTotal());
		result.setRows(list);
		return result;
	}

	/**
	 * ajax查询权限到下拉列表
	 * 
	 * @return
	 */
	@RequestMapping("/functionListajax")
	@ResponseBody
	public List<HxAuthFunction> functionListajax() {
		return functionService.functionListajax();
	}

	/**
	 * 增加权限
	 * 
	 * @param function
	 * @return
	 */
	@RequestMapping("/functionAdd")
	@ResponseBody
	public HXResult functionAdd(HxAuthFunction function) {
		String id = IDUtils.getNumStringId();
		function.setId(id);
		// 判断pid是否是空字符串
		if ("".equals(function.getpId())) {
			function.setpId(null);
		}
		try {
			functionService.functionAdd(function);
			return HXResult.ok("增加权限成功！");
		} catch (Exception e) {
			e.printStackTrace();
			return HXResult.build(500, "增加权限失败！");
		}
	}

	/**
	 * 更新权限
	 * 
	 * @param function
	 * @return
	 */
	// http://192.168.0.254:8080/HXManager/admin/functionUpdate
	@RequestMapping("/functionUpdate")
	@ResponseBody
	public HXResult functionUpdate(HxAuthFunction function) {
		try {
			functionService.functionUpdate(function);
			return HXResult.ok("更新权限成功！");
		} catch (Exception e) {
			e.printStackTrace();
			return HXResult.build(500, "更新权限失败！");
		}
	}

	@RequestMapping("/functionDelete")
	@ResponseBody
	public HXResult functionDelete(String ids) {
		try {
			String[] idStrings = ids.split(",");
			for (String id : idStrings) {
				functionService.deleteUserById(id);
			}
			return HXResult.ok("删除权限成功！");
		} catch (Exception e) {
			return HXResult.ok("删除权限失败！");
		}

	}

	/*
	 * 管理员相关页面跳转
	 */
	@RequestMapping("/{path}")
	public String goPath(@PathVariable String path) {
		return "admin/" + path;
	}

}
